# -*- coding: utf8 -*-
from PIL import Image


def smartSliceImg(img, outDir, ii,count=5, p_w=1):
    '''
    :param img:
    :param outDir:
    :param count: 图片中有多少个图片
    :param p_w: 对切割地方多少像素内进行判断
    :return:
    '''
    # w, h = img.size
    # pixdata = img.load()
    # 这里对数据预先处理，将头尾多余部分去掉
    # img.crop((45,0,175,50)).save(outDir + "test_split.png")
    new_image = img.crop((45, 0, 175, 50))
    w, h = new_image.size
    pixdata = new_image.load()
    eachWidth = int(w / count)  # eachWidth: 切割偏移量
    beforeX = 0
    for i in range(count):
        allBCount = []
        nextXOri = (i + 1) * eachWidth # 记录下一个切割点的起始位置
        for x in range(nextXOri - p_w, nextXOri + p_w):
            # 对切割后的小图像进行再次处理
            if x >= w:
                x = w - 1
            if x < 0:
                x = 0
            b_count = 0
            for y in range(h):
                if pixdata[x, y] == 0:
                    b_count += 1
            allBCount.append({'x_pos': x, 'count': b_count})
        # 对切分后的图片进行排序（从0-255进行排序）
        sort = sorted(allBCount, key=lambda e: e.get('count'))
        nextX = sort[0]['x_pos']
        box = (beforeX, 0, nextX, h)
        new_image.crop(box).resize((25,50)).save(outDir + str(ii) + "_" + str(i) + ".png")
        beforeX = nextX
        # print(allBCount)

for ii in  range(1000):
    path = "process_image1000\\" + 'new_'+str(ii) + ".jpg"
    img = Image.open(path)
    outDir = 'split_image1000/'
    print '正在处理第 {} 张图片'.format(ii)
    smartSliceImg(img, outDir, ii)


print('end'.center(50,'*'))